package com.lehecai.ucenter.action.user;

import java.util.ArrayList;
import java.util.List;

import com.lehecai.ucenter.action.BaseAction;
import com.lehecai.ucenter.bean.PermissionBean;
import com.lehecai.ucenter.bean.UserSessionBean;
import com.lehecai.ucenter.constant.GlobalConstant;
import com.lehecai.ucenter.entity.permission.Permission;

public class MainAction extends BaseAction {
	private static final long serialVersionUID = -8830679912602886965L;
	private UserSessionBean userSessionBean;
	private List<PermissionBean> permissionBeans;
	
	public String handle() {
		userSessionBean = (UserSessionBean)super.getSession().get(GlobalConstant.USER_SESSION_KEY);
		if (userSessionBean == null) {
			logger.error("session丢失");
			super.setErrorMessage("您的session丢失，请重新登录");
			return "index";
		}
		permissionBeans = new ArrayList<PermissionBean>();
		List<Permission> ownPermissions = userSessionBean.getPermissions();
		for (Permission permission : ownPermissions) {
			PermissionBean permissionBean = new PermissionBean();
			if(permission.getParentId() == 0){
				permissionBean.setPermission(permission);
				permissionBeans.add(permissionBean);
			}
		}
		
		for (PermissionBean bean : permissionBeans){
			List<Permission> subPermissions = getSelfPermissionItems(bean.getPermission(),ownPermissions);
			bean.setSubPermissions(subPermissions);
		}
		return "login";
	}
	
	public List<Permission> getSelfPermissionItems(Permission parent, List<Permission> permissions) {
		List<Permission> list = new ArrayList<Permission>();
		for (Permission permission : permissions) {
			if (permission.getParentId().longValue() ==  parent.getId().longValue() && permission.isMenuItem()) {
				list.add(permission);
			}
		}
		return list;
	}

	public UserSessionBean getUserSessionBean() {
		return userSessionBean;
	}

	public void setUserSessionBean(UserSessionBean userSessionBean) {
		this.userSessionBean = userSessionBean;
	}

	public List<PermissionBean> getPermissionBeans() {
		return permissionBeans;
	}

	public void setPermissionBeans(List<PermissionBean> permissionBeans) {
		this.permissionBeans = permissionBeans;
	}

}
